import React from 'react'
import PropTypes from 'prop-types'
import {routerRedux} from 'dva/router'
import {connect} from 'dva'
import {Button, Col, message, Popconfirm, Row, Tabs} from 'antd'
import {Page} from 'components'
import queryString from 'query-string'
import List from './components/List'
import Filter from './components/Filter'
import {HighQualityModal} from 'components/WeChat'
import FriendCircle from 'components/FriendCircle'

const {TabPane} = Tabs


const HighQualityFriendCircle = ({
                      location, employee, discover, dispatch, highQualityFriendCircle, loading,
                    }) => {

  const {query, pathname} = location
  const {
    list, pagination, activeKey, empDataSource: dataSource,
  } = highQualityFriendCircle
  const {
    departments,
    roles,
    modalVisible,
    currentItem,
    list: empList,
    pagination: empPage,
    selectedRowKeys,
    selectedRows,
  } = employee
  const {discoveriesVisible} = discover

  const handleRefresh = (newQuery) => {
    dispatch(routerRedux.push({
      pathname,
      search: queryString.stringify({
        ...query,
        ...newQuery,
      }),
    }))
  }

  const handleTabChange = key => {
    dispatch({
      type: 'highQualityFriendCircle/updateState',
      payload: {
        activeKey: key,
      },
    })
  }



  const listProps = {
    rowKey: 'id',
    dataSource: list,
    loading: loading.effects['highQualityFriendCircle/query'],
    pagination: false,
    location,
    onChange (page) {
      handleRefresh({
        current: page.current,
        size: page.pageSize,
      })
    },
    onDeleteItem (id) {
      dispatch({
        type: 'highQualityFriendCircle/delete',
        payload: {id: id},
      })
        .then(() => {
          handleRefresh({
            current: (list.length === 1 && pagination.current > 1) ? pagination.current - 1 : pagination.current,
          })
          message.success("删除成功")
        })
    },
    onEditItem (item) {
      console.log(item)
      const viewerList = item.viewerList ? item.viewerList : []
      dispatch({
        type: 'employee/query',
        payload: {
          current: 1,
          size: 10,
        }
      })
      dispatch({
        type: 'employee/updateState',
        payload: {
          modalVisible: true,
          currentItem: item,
          selectedRowKeys: viewerList.map(_ => _.id),
          selectedRows: viewerList,
        },
      })
    },
    rowSelection: {
      selectedRowKeys,
      onChange: (keys) => {
        dispatch({
          type: 'highQualityFriendCircle/updateState',
          payload: {
            selectedRowKeys: keys,
          },
        })
      },
    },
    showDiscoveries (record) {
      const {customer, friendCircle} = record
      if (!customer || !friendCircle) {
        message.error("数据异常，请联系管理员")
      }

      console.log(customer)
      dispatch({
        type: 'discover/showDiscoveries',
        payload: {
          author: {
            id: record['wxId'],
            name: customer['friendRemark'] || customer['friendNickname'],
            dfriendId: customer['dfriendWxId'],
            avatar: customer['icon'] || '/public/logo@300.png',
            signature: customer['signature'] || '没有获取到个性签名',
            background: '/public/default-cover.jpg',
            startTime: friendCircle['releaseTime'],
            snsId: friendCircle['id']
          },
        },
      })
    },
  }

  const filterProps = {
    filter: {
      ...query,
    },
    onFilterChange (value) {
      handleRefresh({
        ...value,
        current: 1,
      })
    },
    onAdd () {
      dispatch({
        type: 'highQualityFriendCircle/showModal',
        payload: {
          modalType: 'create',
        },
      })
    },
  }

  const handleDeleteItems = () => {
    dispatch({
      type: 'highQualityFriendCircle/multiDelete',
      payload: {
        ids: selectedRowKeys,
      },
    })
      .then(() => {
        handleRefresh({
          current: (list.length === selectedRowKeys.length && pagination.current > 1) ? pagination.current - 1 : pagination.current,
        })
        message.success("删除成功")
      })
  }

  const modalProps = {
    visible: modalVisible,
    title: '优质朋友圈记录',
    list: empList,
    departments,
    roles,
    currentItem,
    pagination: empPage,
    onChange (page) {
      dispatch({
        type: "employee/query",
        payload: {
          current: page.current,
          size: page.pageSize,
        },
      })
    },
    handleSearch (data) {
      if (data) {
        dispatch({
          type: "employee/query",
          payload: {
            ...data,
            current: 1,
            size: 10,
          },
        })
      } else {
        dispatch({
          type: "employee/query",
        })
      }
    },
    handleCancel () {
      dispatch({
        type: "employee/updateState",
        payload: {
          modalVisible: false,
          selectedRowKeys: [],
          selectedRows: [],
        },
      })
    },
    rowSelection: {
      selectedRowKeys,
      onChange: (keys, selectedRows) => {
        dispatch({
          type: 'employee/updateState',
          payload: {
            selectedRowKeys: keys,
            selectedRows: selectedRows,
          },
        })
      },
    },
    handleOk (description, hid) {
      if (selectedRows.length <= 0) {
        message.warn("请至少选择一位员工查看权限")
        return
      }

      const data = {
        id: currentItem['id'],
        type: 0,
        friendCircleId: currentItem.friendCircle ? currentItem.friendCircle.id : null,
        description,
        empId: selectedRows.map(item => Number(item.id))
      }

      dispatch({
        type: 'highQualityFriendCircle/create',
        payload: data
      }).then(() => {
        dispatch({
          type: "employee/updateState",
          payload: {
            modalVisible: false,
            selectedRowKeys: [],
            selectedRows: [],
            currentItem: {},
          },
        })
      })
    },
  }

  return (
    <Page inner>
      <Tabs activeKey={activeKey} onChange={handleTabChange}>
        <TabPane tab={'优质朋友圈'} key={'group_list'}>
          <Filter {...filterProps}/>
          {
            selectedRowKeys.length > 0 &&
            <Row style={{marginBottom: 24, textAlign: 'right', fontSize: 13}}>
              <Col>
                {`选中了 ${selectedRowKeys.length} 条数据`}
                <Popconfirm title="确定要删除这些数据吗?" placement="left" onConfirm={handleDeleteItems}>
                  <Button type="primary" style={{marginLeft: 8}}>删除</Button>
                </Popconfirm>
              </Col>
            </Row>
          }
          <List {...listProps} />
          {modalVisible && <HighQualityModal {...modalProps} />}
          {discoveriesVisible && <FriendCircle requireRecommend={false}/>}
        </TabPane>
      </Tabs>
    </Page>
  )
}

HighQualityFriendCircle.propTypes = {
  highQualityFriendCircle: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
}

export default connect(({highQualityFriendCircle, discover, employee, loading}) => ({highQualityFriendCircle, discover, employee, loading}))(HighQualityFriendCircle)
